import axios from "axios";
import { BASE_URL } from "./url";
import { getToken,removeToken } from "./auth";

const API = axios.create({
  baseURL: BASE_URL
});
// 添加请求拦截器
API.interceptors.request.use(config => {
  const { url } = config;
  // 判断url是否是以/user开头，且不是以/user/login和/user/registered开头的，就添加token值
  if (
    url.startsWith("/user") &&
    !url.startsWith("/user/login") &&
    !url.startsWith("/user/registered")
  ) {
    // 添加请求头
    config.headers.Authorization = getToken();
  }
  return config;
});
API.interceptors.response.use(config => {
    const {data:{status}} = config
    // 如果状态码=== 400时，移除token
    if (status === 400) {
        removeToken()
    }
    return config
})
export { API };
